/* eslint-disable camelcase */
const { Service } = require('egg')
const iconv = require('iconv-lite') // 导入iconv-lite模块
const { tableToList } = require('../utils/tools')

module.exports = class emptyroomService extends Service {
  /**
    * 爬取空闲教室
   * @param {string} term  学期
   * @param {string} zc    周次
   * @param {string} week  星期
   * @param {{label:string, value:string}} building 教学楼
   * @param {string} school_id 校区id
   * @return {Array} *
   */
  async table(term, zc = '', week = '', school_id = '', building = { label: '', value: '' }) {
    term = '2023-2024-2'// term前端传值
    zc = '6'// 周次前端传值
    week = '1'// 星期前端传值
    school_id = '1'// 校区前端传值
    building.value = '112'// 教学楼编号
    building.label = '附属第二幼儿园'// 教学楼名称
    const [xn, , xqRaw] = term ? term.split('-') : ['', '', '']
    const xq_m = xqRaw === '1' ? '0' : '1'
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/cssfjw/kbbp/dykb.fzcjcckkxjsi_data.jsp`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        xn, // 学年
        txtZC: zc, // 周次
        selZ: week, // 星期起点
        selZ2: week, // 星期终点
        selXQ: school_id, // 校区(南校区1，北校区2)
        sel_lf: building.value, // 教学楼编号
        xq_m, // 学期
        seldsz: '', // 单双周
      },
      headers: {
        Cookie,
        referer: 'http://58.20.34.197:10115/cssfjw/kbbp/dykb.fzcjcckkxjsi.html?menucode=SB11',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const gbkString = iconv.decode(res.data, 'gbk')
    if (res.status === 200) {
      try {
        const table1 = tableToList(gbkString, 'body')
        table1.splice(0, 1)
        const tem = []
        table1.forEach((item) => { item.forEach((item2, index2) => {
          if (item2 && index2 % 2 === 0) {
            // console.log('item2', item2);
            tem.push(item2)
          } }) })

        return {
          campus_id: '0021',
          school_id,
          zc,
          week,
          building: building.label,
          data: { tem },
        }
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return {}
  }
}
